package cn.bbstone.pisces2.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.bbstone.pisces2.client.base.RspDispatcher;
import cn.bbstone.pisces2.client.util.MsgUtil;
import cn.bbstone.pisces2.listener.OpEnum;
import cn.bbstone.pisces2.listener.OpUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class FileClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
	private static Logger log = LoggerFactory.getLogger(FileClientHandler.class);

	public FileClientHandler() {
	}
	
	

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);

		// notify UI load connectionInfo
		// (Notice: here get localAddress, different with server get remoteAddress)
//		CtxUtil.addConnInfo(ctx.channel().localAddress().toString());
		OpUtil.execListener(OpEnum.s5_client_connected, ctx.channel().localAddress().toString());

		// NOTICE: support multi-client
		MsgUtil.firstReqListInfo(ctx);
		// the very first request for fli.idx file info
//        ctx.writeAndFlush(MsgUtil.buildReq(BFileCmd.REQ_LIST_INFO, 0L));
	}

	public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
		log.debug("client recv total readableBytes: {}", msg.readableBytes());
		RspDispatcher.dispatch(ctx, msg);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		super.channelInactive(ctx);

		// notify UI load connectionInfo
		// (Notice: here get localAddress, different with server get remoteAddress)
//    	CtxUtil.removeConnInfo(ctx.channel().localAddress().toString());
    	OpUtil.execListener(OpEnum.s6_client_disconnected, ctx.channel().localAddress().toString());
	}

}
